How I use RegExp in my Java program? [migrated]
Posted
by
MIH1406
on Programmers
See other posts from Programmers
or by MIH1406
Published on 2012-11-30T05:23:43Z
Indexed on
2012/11/30
11:21 UTC
Read the original article
Hit count: 368
I have the following string examples:
00001 1 12 123
00002 3 7 321
00003 99 23 332
00004 192 50 912
In a separate text file. Numbers are separated by tabs not spaces.
I tried to read the file and print each line if it matches a given RegExp, but I could not find the suitable RegExp for these lines.
private static void readFile() {
String fileName = "processes.lst";
FileReader file = null;
String result = "";
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line = null;
String regEx = "[0-9]\t[0-9]\t[0-9]\t[0-9]";
while((line = reader.readLine()) != null) {
if(line.matches(regEx)) {
result += "\n" + line;
}
}
} catch(Exception e) {
System.out.println(e.getMessage());
} finally {
if(file != null)
try {
file.close();
} catch(Exception e) {
System.out.println(e.getMessage());
}
}
System.out.println(result);
}
I ended up without any string being printed!!
© Programmers or respective owner